package com.neo.tiny.admin.api.oauth;

import com.neo.tiny.admin.api.user.UserAuthApi;
import com.neo.tiny.admin.vo.user.AuthUserDetails;
import com.neo.tiny.common.exception.WebApiException;
import com.neo.tiny.secrity.model.AdminUserDetails;
import com.neo.tiny.secrity.service.AdminUserDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author yqz
 * @Description
 * @CreateDate 2022/11/11 11:57
 */
@Service
@AllArgsConstructor
public class UserAuthApiImpl implements UserAuthApi {


    private final AdminUserDetailsService adminUserDetailsService;

    private final PasswordEncoder passwordEncoder;


    @Override
    public AuthUserDetails authenticate(String username, String password) {

        UserDetails userDetails = adminUserDetailsService.loadUserByUsername(username);
        AdminUserDetails adminUserDetails = (AdminUserDetails) userDetails;
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new WebApiException("用户名或密码错误");
        }
        if (!userDetails.isEnabled()) {
            throw new WebApiException("账户被禁用");
        }

        return new AuthUserDetails(adminUserDetails.getSysUser().getId(), userDetails.getUsername(), null);

    }
}
